package com.fxcalibre.fxml.control;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;

import com.fxcalibre.db.beans.Person;
import com.fxcalibre.fxml.control.events.DataChangedEvent;
import com.fxcalibre.fxml.view.FXMLViewLoader;
import com.fxcalibre.hibernate.dao.PeopleDAO;

public class PeopleListPanel extends BorderPane
{
	@FXML
	TableView<Person> peopleTable;
	@FXML
	private TableColumn<Person, String> nameColumn;
	@FXML
	PersonDetail personDetail;

	ObservableList<Person> tableData = FXCollections.observableArrayList(PeopleDAO.getPeople());

	public PeopleListPanel()
	{
		FXMLViewLoader.load(this, "PeopleListPanel.fxml");

		peopleTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
		peopleTable.setItems(tableData);
		nameColumn.setCellValueFactory(new PropertyValueFactory<Person, String>("name"));

		// Listen for selection changes
		peopleTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Person>()
		{

			@Override
			public void changed(ObservableValue<? extends Person> observable, Person oldValue, Person newValue)
			{
				personDetail.setPerson(newValue);
			}
		});

		addEventHandler(DataChangedEvent.DATA_CHANGED, new EventHandler<DataChangedEvent>()
		{
			@Override
			public void handle(DataChangedEvent event)
			{
				if (event.getEventType().equals(DataChangedEvent.DATA_CHANGED))
				{
					System.out.println("DATA CHANGED!!!!!");
					reload();
				}
			}
		});

	}

	@FXML
	private void addPerson(ActionEvent event)
	{
		System.out.println("addPerson!!");
		PersonDetail personDetailForPopUp = new PersonDetail();
		personDetailForPopUp.setPerson(new Person());
		personDetailForPopUp.showInStage();
		reload();
	}

	private void reload()
	{
		tableData.clear();
		tableData.addAll(PeopleDAO.getPeople());
	}

}
